//
// Created by 69566 on 25-8-18.
//

#include "data_manager.h"
#include <string.h>
xx_data_t data_acq = {0};
data_info_t data_acq_info[] = {
    [0] = {offsetof(xx_data_t, data1), sizeof(uint8_t)},
    [1] = {offsetof(xx_data_t, data2), sizeof(uint8_t)},
    [2] = {offsetof(xx_data_t, data3), sizeof(uint16_t)},
    [3] = {offsetof(xx_data_t, data4), sizeof(uint8_t)},
};

static uint32_t data_get_byte(data_index_e index) {
  uint8_t *ptr = (uint8_t *)&data_acq + data_acq_info[index].offset;
  uint32_t val = 0;
  memcpy(&val, ptr, data_acq_info[index].size);
  return val;
}
static uint8_t data_get_bit(data_index_e index) {
  uint32_t idx = (index >> 8) & 0xFFF;
  uint32_t bit_len = (index >> 4) & 0x0F;
  uint32_t bit_off = index & 0x0F;

  uint32_t val = data_get_byte((data_index_e)idx);
  return (val >> bit_off) & ((1 << bit_len) - 1);
}
uint32_t data_get(data_index_e index) {
  if (index > DATA_MAX_ALL) {
    printf("index error %d\n", index);
    return;
  }
  if (index < DATA_MAX) {
    return data_get_byte(index);
  } else {
    return data_get_bit(index);
  }
}
static void data_set_byte(data_index_e index, uint32_t value) {
  uint8_t *ptr = (uint8_t *)&data_acq + data_acq_info[index].offset;
  memcpy(ptr, &value, data_acq_info[index].size);
}
static void data_set_bit(data_index_e index, uint8_t value) {
  uint32_t idx = (index >> 8) & 0xFFF;
  uint32_t bit_len = (index >> 4) & 0x0F;
  uint32_t bit_off = index & 0x0F;

  uint32_t val = data_get_byte((data_index_e)idx);
  uint32_t mask = ((1 << bit_len) - 1) << bit_off;
  val = (val & ~mask) | ((value << bit_off) & mask);
  data_set_byte((data_index_e)idx, val);
}
void data_set(data_index_e index, uint8_t value) {
  if (index > DATA_MAX_ALL) {
    printf("index error %d\n", index);
    return;
  }
  if (index < DATA_MAX) // 根据枚举来判断是写字节还是位
  {
    data_set_byte(index, value);
  } else {
    data_set_bit(index, value);
  }
}